package download

import (
	"context"
	"encoding/json"
	"log"
	"os"
	"path"
	"strings"
	"sync"

	"github.com/Unknwon/com"
	"smartconn.cc/liugen/ado/downloading"
	"smartconn.cc/tosone/ra_main/common"
	"smartconn.cc/tosone/ra_main/config"
	"smartconn.cc/tosone/ra_main/store"
	"smartconn.cc/tosone/ra_main/taskMgr"
)

const serviceName = "download"

var err error

func init() {
	var locker sync.Mutex
	channel := make(chan common.ServiceCommand, 1)
	if !com.IsDir(path.Join(config.TaskDir, serviceName)) {
		err = os.MkdirAll(path.Join(config.TaskDir, serviceName), 0755)
		if err != nil {
			log.Println(err)
			return
		}
	}
	taskMgr.Register(serviceName, channel)
	go func() {
		for {
			select {
			case control := <-channel:
				switch control.Cmd {
				case "start":
					locker.Lock()
					download()
					locker.Unlock()
				}
			}
		}
	}()
}

func download() {
	var id, taskContent, downloadDest string
	var content common.TaskContentDownload
	id, taskContent, err = store.GetATask(serviceName)
	if err != nil {
		log.Println(err)
		return
	}
	err = json.Unmarshal([]byte(taskContent), &content)
	if err != nil {
		log.Println(err)
		return
	}
	file := content.File
	if content.Path != "" {
		downloadDest = content.Path
	} else {
		downloadDest = path.Join(config.TaskDir, "download")
	}
	if file[0:6] != "oss://" {
		log.Printf("Not oss protocal: %s\n", file)
		return
	}
	fileinfo := strings.Split(file[6:], "/")
	if len(fileinfo) != 2 {
		log.Printf("Download get an error args: %s\n", file)
		return
	}
	bucket := fileinfo[0]
	filename := fileinfo[1]
	ctx := context.TODO()
	err := downloading.OssDownload(ctx, config.OSSInfo["ossEndpoint"], config.OSSInfo["aliyunAccessKeyId"], config.OSSInfo["aliyunAccessKeySecret"], bucket, filename, downloadDest, 3000, 10*1024, 10)
	if err != nil {
		log.Println("Download error.")
		log.Println(err)
		return
	}
	store.RemoveTask(id)
	var uncompressTaskContent common.TaskContentUncompress
	if content.Uncompress {
		uncompressTaskContent.File = downloadDest
		uncompressTaskContent.Path = content.UncompressPath
		taskContent, err := json.Marshal(uncompressTaskContent)
		if err != nil {
			log.Println(err)
			return
		}
		store.AddTask("uncompress", string(taskContent))
	}
	if content.StoreTipsAudioHash != "" {
		store.AddTipsAudio(content.StoreTipsAudioHash, content.Path)
	}
}
